import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { projectAPI } from '@/api/project'
import { ElMessage } from 'element-plus'

export interface ProjectStats {
  total_projects: number
  active_projects: number
  completed_projects: number
  overdue_projects: number
  archived_projects?: number
  planning_projects?: number
  paused_projects?: number
  cancelled_projects?: number
}

export const useProjectStatsStore = defineStore('projectStats', () => {
  // 状态
  const stats = ref<ProjectStats>({
    total_projects: 0,
    active_projects: 0,
    completed_projects: 0,
    overdue_projects: 0,
    archived_projects: 0,
    planning_projects: 0,
    paused_projects: 0,
    cancelled_projects: 0
  })

  const loading = ref(false)
  const error = ref<string | null>(null)
  const lastFetchTime = ref<number>(0)
  const cacheTimeout = 5 * 60 * 1000 // 5分钟缓存

  // 计算属性
  const isDataFresh = computed(() => {
    return Date.now() - lastFetchTime.value < cacheTimeout
  })

  // 获取统计数据
  const fetchStats = async () => {
    // 如果数据已存在且不超过5分钟，直接返回缓存数据
    if (stats.value && lastFetchTime.value && Date.now() - lastFetchTime.value < 5 * 60 * 1000) {
      // 使用缓存的项目统计数据
      return stats.value
    }

    // 如果正在加载中，等待加载完成
    if (loading.value) {
      // 项目统计数据正在加载中，等待完成
      return new Promise((resolve) => {
        const unwatch = watch(loading, (newLoading) => {
          if (!newLoading) {
            unwatch()
            resolve(stats.value)
          }
        })
      })
    }

    loading.value = true
    error.value = null

    try {
      // 开始获取项目统计数据
      const response = await projectAPI.getProjectStats()

      // 提取的统计数据
      const statsData = response?.data || {}
      
      stats.value = {
        total_projects: statsData?.total_projects || 0,
        active_projects: statsData?.active_projects || 0,
        completed_projects: statsData?.completed_projects || 0,
        overdue_projects: statsData?.overdue_projects || 0,
        archived_projects: statsData?.archived_projects || 0,
        planning_projects: statsData?.projects_by_status?.planning || 0,
        paused_projects: statsData?.projects_by_status?.on_hold || 0,
        cancelled_projects: statsData?.projects_by_status?.cancelled || 0
      }

      lastFetchTime.value = Date.now()

      return stats.value
    } catch (err) {
      console.error('获取项目统计失败:', err)
      error.value = err instanceof Error ? err.message : '获取项目统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 刷新统计数据
  const refreshStats = () => {
    clearCache()
    return fetchStats()
  }

  // 清除缓存
  const clearCache = () => {
    lastFetchTime.value = 0
  }

  // 重置统计数据
  const resetStats = () => {
    stats.value = {
      total_projects: 0,
      active_projects: 0,
      completed_projects: 0,
      overdue_projects: 0,
      archived_projects: 0,
      planning_projects: 0,
      paused_projects: 0,
      cancelled_projects: 0
    }
    lastFetchTime.value = 0
  }

  return {
    // 状态
    stats,
    loading,
    lastFetchTime,
    
    // 计算属性
    isDataFresh,
    
    // 方法
    fetchStats,
    refreshStats,
    clearCache,
    resetStats
  }
})